<template>
  <div>
    <div class="app-container" id="app-container">
      <div id="flowWrap" ref="flowWrap" class="flow-wrapper">
        <div id="table-flow" ref="tableFlow" :style="{ scale: scale }">
          <TableNode v-for="node in json.nodes" :id="node.name" :key="node.name" :node="node" ref="cardbox"
            @scrollevent="scrollevent" />
        </div>
      </div>
      <!-- ⬆️按钮组 -->
      <div class="toolsBox">
        <template v-for="item in buttonGroup">
          <el-tooltip class="item" effect="dark" :content="item.label" placement="bottom" v-if="item.show">
            <span :class="item.icon" @click="clickBtn(item.type)"></span>
          </el-tooltip>
        </template>
      </div>
    </div>
    <!-- 🫱表格 -->
    <el-drawer :visible.sync="tableBox" direction="rtl" size="60%">
      <template slot="title">
        <div>
          <el-button type="info" icon="el-icon-back" size="mini" circle @click="closeBox"></el-button> <span>{{ titleTexe
          }}</span>
        </div>
      </template>
      <div v-loading="loadingDrawer">
        <div id="formBox" v-show="serchBox">
          <div id="serch">
            <span>
              查询设置
            </span>
          </div>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="源表关键字">
              <el-input v-model="formInline.SourceTableKey"></el-input>
            </el-form-item>
            <el-form-item label="目标表关键字">
              <el-input v-model="formInline.TargetTableKey"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div id="resultlist">
          <div id="serch">
            <span>
              结果列表
            </span>
          </div>
        </div>
        <el-table :data="gridData" :header-cell-style="{ backgroundColor: '#F2F6FC' }">
          <el-table-column v-for="(item, index) in tibleList" :key="index" :prop="item.prop" :label="item.label"
            :align="item.align">
          </el-table-column>
          <el-table-column label="下钻" align="center" v-if="serchBox">
            <template slot-scope="scope">
              <i class="el-icon-download" @click="isRow(scope)">
              </i>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-drawer>
  </div>
</template>

<script>
import jsplumbModule from 'jsplumb'
import { commConfig } from './config/jsplumbConfig'
import buttonGroup from './config/buttonGroup'
import buttonMethods from './methods/buttonMethods'
import comm from './methods/comm'
import TableNode from './components/TableNode'
import dataList from "./config/data.json"
const jsplumb = jsplumbModule.jsPlumb
export default {
  name: 'Index',
  components: {
    TableNode
  },
  data() {
    return {
      scale: 1,//缩放
      loadingDrawer: false,
      loading: false,
      printObj: {
        id: 'table-flow',
        popTitle: '数据地图', // 标题
      },
      fullscreen: false,
      jsplumbInstance: null,
      json: {
        nodes: [], edges: []
      },
      buttonGroup: buttonGroup,
      commConfig: commConfig,
      auxiliaryLine: { isShowXLine: false, isShowYLine: false },  //对齐辅助线是否显示
      auxiliaryLinePos: { width: '100%', height: '100%', offsetX: 0, offsetY: 0, x: 20, y: 20 },
      minus: '-', //表名和列名的分割符号
      anchorArr: ['Left', 'Right'],//specified anchor
      // commGrid: 
      tableBox: false,
      gridData: [{
        date: '2016-05-02',
        name: '王小虎',
        dataddresse: '上海市普陀区金沙江路 1518 弄',
        date1: '2016-05-02',
        name1: '王小虎',
        dataddresse1: '上海市普陀区金沙江路 1518 弄',
      }, {
        date: '2016-05-02',
        name: '王小虎',
        dataddresse: '上海市普陀区金沙江路 1518 弄',
        date1: '2016-05-02',
        name1: '王小虎',
        dataddresse1: '上海市普陀区金沙江路 1518 弄',
      }, {
        date: '2016-05-02',
        name: '王小虎',
        dataddresse: '上海市普陀区金沙江路 1518 弄',
        date1: '2016-05-02',
        name1: '王小虎',
        dataddresse1: '上海市普陀区金沙江路 1518 弄',
      }, {
        date: '2016-05-02',
        name: '王小虎',
        dataddresse: '上海市普陀区金沙江路 1518 弄',
        date1: '2016-05-02',
        name1: '王小虎',
        dataddresse1: '上海市普陀区金沙江路 1518 弄',
      }],
      titleTexe: null, //显示表头
      serchBox: false,
      formInline: {
        SourceTableKey: '',
        TargetTableKey: ''
      },
    };
  },
  watch: {
  },
  computed: {
    tibleList() {
      let list = []
      if (this.serchBox) {
        list = [
          {
            prop: "date", label: "源库名", align: "center"
          },
          {
            prop: "name", label: "源表名", align: "center"
          },
          {
            prop: "dataddresse", label: "源表中文名", align: "center"
          },
          {
            prop: "date1", label: "目标库名", align: "center"
          },
          {
            prop: "name1", label: "目标表名", align: "center"
          },
          {
            prop: "dataddresse1", label: "目标表中文名", align: "center"
          }
        ]
      } else {
        list = [
          {
            prop: "date", label: "源表名", align: "center"
          },
          {
            prop: "name", label: "源字段", align: "center"
          },
          {
            prop: "dataddresse", label: "源字段中文名", align: "center"
          },
          {
            prop: "date1", label: "目标表名", align: "center"
          },
          {
            prop: "name1", label: "目标字段名", align: "center"
          },
          {
            prop: "dataddresse1", label: "目标字段中文名", align: "center"
          }
        ]
      }
      return list
    }
  },
  mounted() {
    this.renderDefaultLineage()
  },
  beforeDestroy() {
    this.jsplumbInstance.reset()
  },
  methods: {
    //关闭弹窗
    closeBox() {
      if (this.serchBox) {
        this.tableBox = false
      } else {
        this.loadingDrawer = true
        this.titleTexe = '表间关系'
        this.serchBox = true
        this.tableBox = true
        this.loadingDrawer = false
      }
    },
    //查询
    onSubmit() {
      alert('查询')
    },
    //重置
    resetForm() {
      alert('重置')
    },
    //下钻
    isRow(scope) {
      this.loadingDrawer = true
      console.log(scope, 'scope');
      this.titleTexe = '字段间关系'
      this.serchBox = false
      this.loadingDrawer = false
    },
    //滚轮
    scrollevent() {
      //清缓存
      this.jsplumbInstance.reset()
      //拖拽渲染
      this.drawing(this.anchorArr)
    },
    renderDefaultLineage() {
      if (this.buttonGroup[0].show) {
        let arrAy = require('../views/config/sampleData.json')
        this.json.nodes = arrAy.nodes
        this.json.edges = arrAy.edges
        this.buttonGroup[0].show = false


      } else {
        this.json.nodes = dataList.nodes
        this.json.edges = dataList.edges
      }
      this.init();
    },
    //初始化
    init() {
      this.fixNodesPosition()
      this.$nextTick(() => {
        this.initialize()
      })
    },
    //真正的初始化
    initialize() {
      jsplumb.ready(() => {
        //设置jsplumb实例、设置jsplumb默认配置、设置jsplumb容器
        this.jsplumbInstance = jsplumb.getInstance().importDefaults(commConfig)
        this.jsplumbInstance.setContainer('table-flow')
        // 先清除一下画布,防止缓存
        this.jsplumbInstance.reset();
        this.drawing(this.anchorArr)
        // 会使整个jsPlumb立即重绘。
        this.jsplumbInstance.setSuspendDrawing(false, true);
        //初始化缩放
        this.initPanZoom()
      })
    },
    // 绘制
    drawing(anchorArr) {
      if (this.json.nodes && this.json.edges) {
        //判断是否元素在区域内，然后循环连线
        //1 绘制节点信息
        this.json.nodes.forEach(node => {
          //显示返回按钮
          if (node.type == 'tab') {
            this.buttonGroup[0].show = true
          }
          //使节点可拖动
          this.draggableNode(node.name)
          node.fields.forEach(field => {
            this.addEndpoint(node.name + "-" + field.name, anchorArr)
          })
        })

        //鼠标点击连线事件
        this.jsplumbInstance.unbind("click");
        this.jsplumbInstance.bind("click", conn => {
          const gosu = conn.sourceId.split(this.minus)[0]
          const tosu = conn.targetId.split(this.minus)[0]
          const gosuitem = conn.sourceId.split(this.minus)[1]
          const tosuitem = conn.targetId.split(this.minus)[1]
          if (dataList.nodes[0].type == "tab") {
            this.loadingDrawer = true
            this.titleTexe = '表间关系'
            this.serchBox = true
            this.tableBox = true
            return this.loadingDrawer = false
          }
          //清空画布
          this.clear()
          let sf = [
            {
              "name": gosu,
              "type": "tab",
              "color": "#000388",
              "imageSrc": "image1",
              "fields": [{
                "name": gosuitem
              },
              ],
              "top": 135,
              "left": 0
            },
            {
              "name": tosu,
              "type": "tab",
              "imageSrc": "image3",
              "color": "#E18800",
              "fields": [{
                "name": tosuitem
              }
              ],
              "top": 135,
              "left": 450
            },
          ]
          //查找连线配置
          let ef = [
            {
              "from": {
                "name": gosu,
                "field": gosuitem
              },
              "to": {
                "name": tosu,
                "field": tosuitem
              }
            }
          ]
          dataList.nodes = sf
          dataList.edges = ef
          this.refresh();
        })

        //2 绘制节点间连线
        this.json.edges.forEach(edge => {
          let from = edge.from.name + '-' + edge.from.field + '-' + "Right",
            to = edge.to.name + '-' + edge.to.field + '-' + 'Left'
          //动态获取元素的坐标位置
          let itemDivform = edge.from.name + '-' + edge.from.field//起点
          const divContentform = document.getElementById(itemDivform).getBoundingClientRect();//起点每一项数据的数值
          const cardBodyform = document.getElementById(edge.from.name).getBoundingClientRect()//起点每一个card的高度
          let itemDivto = edge.to.name + '-' + edge.to.field//终点
          const divContentTo = document.getElementById(itemDivto).getBoundingClientRect();//终点每一项数据的数值
          const cardBodyTo = document.getElementById(edge.to.name).getBoundingClientRect()//终点每一个card的高度
          if (divContentform.top > cardBodyform.top + 55 && divContentform.bottom < cardBodyform.bottom - 30
            && divContentTo.top > cardBodyTo.top + 55 && divContentTo.bottom < cardBodyTo.bottom - 30
          ) {
            this.connectEndpoint(from, to);
          }
          //绑定事件 鼠标移到连线高亮关联列、线
          this.jsplumbInstance.unbind("mouseover");
          this.jsplumbInstance.bind("mouseover", conn => {
            const to = conn.targetId.split(this.minus)
            let activeNodes = this.findActiveNode(this.json.edges, to[0], to[1])
            activeNodes.forEach(an => {
              const full = an.tbName + this.minus + an.column
              this.jsplumbInstance.getConnections({
                source: full
              })
            })
          });
          //鼠标移走后恢复
          this.jsplumbInstance.unbind('mouseout');
          this.jsplumbInstance.bind("mouseout", conn => {
            const to = conn.targetId.split(this.minus)
            let activeNodes = this.findActiveNode(this.json.edges, to[0], to[1])
            //将所有相关字段恢复默认显示
            activeNodes.forEach(an => {
              const full = an.tbName + this.minus + an.column
              this.jsplumbInstance.getConnections({
                source: full
              })
            })
          });
        })
      }
    },
    ...comm,
    ...buttonMethods
  }

}
  ;
</script>

<style lang="less" scoped>
.app-container {
  display: flex;
  width: 90%;
  height: 750px;
  margin: 20px auto;

  .button-wrapper {
    width: 150px;
    height: 100%;
    border-right: 1px solid #ccc;

    .icon {
      width: 40px;
      height: 40px;
    }

    .node {
      display: flex;
      height: 40px;
      width: 80%;
      margin: 15px auto;
      border-radius: 5px;
      line-height: 40px;
      font-size: 11px;

      &:hover {
        cursor: pointer;
      }

      .log {
        width: 40px;
        height: 40px;
      }

      .name {
        width: 0;
        flex-grow: 1;
      }
    }

    .btnIcon {
      width: 40px;
      height: 40px;
    }
  }

  .flow-wrapper {
    height: 100%;
    position: relative;
    overflow: hidden;
    outline: none !important;
    flex-grow: 1;

    #table-flow {
      position: relative;
      width: 100%;
      height: 100%;

      .auxiliary-line-x {
        position: absolute;
        border: .5px dashed #2ab1e8;
        z-index: 9999;
      }

      .auxiliary-line-y {
        position: absolute;
        border: .5px dashed #2ab1e8;
        z-index: 9999;
      }
    }
  }
}
</style>

<style lang="less" scoped>
// 下面是鼠标移动到连线上时激活的样式
.jtk-connector.jtk-hover {
  z-index: 9999;

  path {
    cursor: pointer !important;
  }
}

.toolsBox {
  position: absolute;
  top: 20px;
  height: 30px;
  width: 320px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px;
  border: 1px solid #000;
  border-radius: 5px;
  box-shadow: 0px 0px 5px 0px rgba(42, 66, 111, 0.7);

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}



#formBox {
  background-color: #F2F6FC;
  padding: 20px 20px 0px 20px;
  margin-bottom: 5px;

  #serch {
    font-size: 15px;
    font-weight: 700;
    margin-bottom: 5px;
  }
}

#resultlist {
  background-color: #F2F6FC;
  padding: 10px 20px 0px 20px;
  font-weight: 700;
}
</style>
